<template>
  <!--左侧树形结构 -->
  <div class="equip-tree-wrap">
    <div class="equip-tree-content">
      <px-input v-model="filterText" style="margin-right: 6px" placeholder="请输入关键字搜索" />
      <px-tooltip content="全部收折" placement="top">
        <px-button v-show="isTreeOpen" link type="primary" icon="ChevronUpRectangle" @click="openOrCloseTree('close')" />
      </px-tooltip>
      <px-tooltip content="全部展开" placement="top">
        <px-button v-show="!isTreeOpen" link type="primary" icon="ChevronDownRectangle" @click="openOrCloseTree('open')" />
      </px-tooltip>
      <px-tooltip content="清除选中" placement="top">
        <px-button style="margin-left: 4px" link type="primary" icon="RefreshLeft" @click="resetCheck" />
      </px-tooltip>
    </div>
    <px-scrollbar class="equip-scroll">
      <px-tree
        ref="treeRef"
        :data="treeData"
        :props="{ children: 'children', label: 'name' }"
        default-expand-all
        node-key="id"
        :filter-node-method="filterNode"
        :expand-on-click-node="false"
        highlight-current
        @node-click="nodeClick"
      />
    </px-scrollbar>
  </div>
</template>
<script lang="ts" setup>
import { searchTreeLedger } from "@/api/erc/equip";
import { onBeforeMount, reactive, ref, toRefs, watch } from "vue";

const treeRef = ref();

const typeCode = defineModel("typeCode", { type: String, default: "0" });
const hasChildren = defineModel("hasChildren", { type: Boolean, default: true });

const state = reactive<any>({
  treeData: [],
  isTreeOpen: false,
  filterText: ""
});
const { treeData, isTreeOpen, filterText } = toRefs(state);

onBeforeMount(() => {
  queryTree();
});

// 监视过滤树的值
watch(filterText, val => {
  treeRef.value!.filter(val);
});

/** 左侧-树形区 **/
// 进入页面加载左侧树
const queryTree = async () => {
  const data: any = await searchTreeLedger({
    name: ""
  });
  // console.log(data, 'queryTree');
  treeData.value = data;
};
// 过滤树数据
const filterNode = (value: string, data: any) => {
  if (!value) return true;
  return data.name.includes(value);
};
// 左侧树添加清除选中按钮
const resetCheck = () => {
  typeCode.value = "";
  const selectedNodes = document.querySelectorAll(".is-current");
  selectedNodes.forEach(element => {
    element.classList.remove("is-current");
  });
};
// 点击左侧树节点，获取facCode，查询设备列表
const nodeClick = (data, node) => {
  hasChildren.value = data.children || data.typeLevel < 2 ? true : false;
  typeCode.value = data.code;
};
// 打开或者关闭树
const openOrCloseTree = type => {
  if (type == "close") {
    isTreeOpen.value = false;
    let nodes = treeRef.value.store._getAllNodes();
    nodes.forEach(item => {
      item.expanded = false;
    });
  } else if (type == "open") {
    isTreeOpen.value = true;
    let nodes = treeRef.value.store._getAllNodes();
    nodes.forEach(item => {
      item.expanded = true;
    });
  }
};
</script>

<style lang="scss" scoped>
@import url("@/views/erc/scss/table-flex-list.scss");
</style>
